<!-- 路线轨迹组件 -->
<template>
  <div class="map-outbox" style="width: 100%;height: 500px;">

    <!--地图容器-->
    <div id="my-container" class="map"></div>

    <!--控制条-->
    <el-row style="top: 5px;" :gutter="20">
      <el-col :span="2">
        <el-button v-if="!isPlaying" type="primary" @click="start()" icon="el-icon-video-play"></el-button>
        <el-button v-if="isPlaying" type="primary" icon="el-icon-video-pause" @click="pause()"></el-button>
      </el-col>
      <el-col :span="19">
        <el-slider v-model="sliderVal" @input="changeValue()"></el-slider>
      </el-col>
      <el-col :span="3">
        <el-select v-model="value" placeholder="请选择" @change="setSpeed()">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-col>
    </el-row>

  </div>
</template>

<script>
import { getByOrder } from '@/api/tws/gis';
import { allTrail  } from '@/api/tws/orderTrail'
import { tsGetDate, dateFormat } from '@/utils/date';
import { accSub, accDiv, accMul } from '@/utils/func';

  export default {
    name:'MapTracker',
    props: {
      orderId: {
        type: String
      }
    },
    data() {
      return {
        trackPath:[],
        isPlaying: false,
        // 巡航轨迹路线对象
        pathSimplifierIns: {},
        // 巡航器对象
        navg: {},
        sliderVal: 0,
        value: 1, //倍速
        speed: 100, //速度
        //开始点
        startMark: [],
        //结束点
        endMark: [],
        options: [{
            value: 1,
            label: "倍速1"
          },
          {
            value: 2,
            label: "倍速2"
          },
          {
            value: 3,
            label: "倍速3"
          },
          {
            value: 4,
            label: "倍速4"
          },
        ],

      };
    },
    watch:{
      // orderId: function(newData, oldData) {
      //   this.reset();
      //   if(newData != null) {
      //     this.$nextTick(function() {
      //       this.getTrack(newData);
      //     })
      //   }
      // },
      deep: true // 可以深度检测到 obj 对象的属性值的变化
    },
    beforeDestroy: function() {
      document.onkeydown = function(e) {};
    },
    methods: {

      dialogClose: function() {
        this.$emit("dialogClose", false);
      },
      // 初始化地图
      initMap: function() {
        var $this = this;
        var map = new AMap.Map('my-container', {
          center: [this.startMark[0],this.startMark[1]], // [纬度，经度]
          resizeEnable: true,
          zoom: 15,
        });
        // 绑定鼠标移动事件，关闭信息窗体
        map.on('mousemove', function() {
          map.clearInfoWindow();
        });
        // //手机轨迹添加开始结束标记点
        // if ($this.startMark != null){
        //   var start = new AMap.Marker({
        //     position: [$this.startMark[0],$this.startMark[1]],
        //     title:'start'
        //   })
        //   map.add(start)
        // }
        if ($this.endMark != null){
          var end = new AMap.Marker({
            position: [$this.endMark[0],$this.endMark[1]],
            title:'end'
          })
          map.add(end)
        }
        AMapUI.load(['ui/misc/PathSimplifier', 'lib/$'], function(PathSimplifier, $) {
          if (!PathSimplifier.supportCanvas) {
            alert('当前环境不支持 Canvas！');
            return;
          }
          //创建一个巡航轨迹路线
          $this.pathSimplifierIns = new PathSimplifier({
            zIndex: 100, //地图层级，
            map: map, //所属的地图实例
            //巡航路线轨迹列表
            getPath: function(pathData, pathIndex) {
              return pathData.path;
            },
            //hover每一个轨迹点，展示内容
            // pathIndex: 路线的下标
            // pointIndex: 轨迹点的下标，如果不是轨迹点则为undefined
            getHoverTitle: function(pathData, pathIndex, pointIndex) {
              if (pointIndex >= 0) {
                // 获取当前点的地址
                $this.pointInfo(map, pathData.path, pointIndex)
                // $this.getAddress(pathData.path[pointIndex]).then(res => {
                //   return '地点：' + res + '，点：' + pointIndex + '/' + pathData.path.length;
                // })
              }
            },
            //自定义样式，可设置巡航器样式，巡航轨迹样式，巡航轨迹点击、hover等不同状态下的样式，不设置则用默认样式，详情请参考api文档
            renderOptions: {
              pathLineStyle: {
                strokeStyle: '#351baf'  // 轨迹颜色
              },
              renderAllPointsIfNumberBelow: 100 //绘制路线节点，如不需要可设置为-1
            }
          });
          //设置数据
          $this.pathSimplifierIns.setData([{
            name: '路线0',
            path: $this.trackPath
          }]);
          //对第一条线路（即索引 0）创建一个巡航器
          $this.navg = $this.pathSimplifierIns.createPathNavigator(0, {
            loop: false, //循环播放
            speed: $this.speed, //巡航速度，单位千米/小时
            pathNavigatorStyle: {
              width: 20,
              height: 30,
              //使用图片
              content: PathSimplifier.Render.Canvas.getImageContent(
                "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png", onload, onerror),
              // strokeStyle: null,
              // fillStyle: null,
              // //经过路径的样式
              // pathLinePassedStyle: {
              //     lineWidth: 5,
              //     strokeStyle: '#FFDC04',
              // }
            }
          });
          $this.navg.on("move", function() {
            let idx = this.getCursor().idx; //走到了第几个点
            let tail = this.getCursor().tail; //至下一个节点的比例位置
            let totalIdx = idx + tail

            // 进度条实时展示tail
            $this.sliderVal = (totalIdx / $this.navg.getPathEndIdx()).toFixed(2) * 100;
          });

        });

      },
      start: function() {
        // stop：停止状态，start之前或者stop之后处于该状态
        // moving：巡航状态，start或者resume之后处于该状态
        // pause：暂停状态，pause之后处于该状态
        this.isPlaying = true;
        if (this.navg.isCursorAtPathEnd()) {
          this.navg.start();
          return
        }
        if (this.navg.getNaviStatus() == "pause") {
          this.navg.resume();
        } else if (this.navg.getNaviStatus() == "stop") {
          this.navg.start();
        }
      },
      pause: function() {
        if (this.navg.getNaviStatus() == "moving") {
          this.navg.pause();
          this.isPlaying = false;
        }
      },
      setSpeed: function() {
        this.navg.setSpeed(this.speed * this.value);
      },
      changeValue: function() {
        // let newVal = typeof(newVal) === 'number' ? val : this.sliderVal
        if(this.sliderVal != 0) {
          let num = parseInt((this.sliderVal / 100) * this.navg.getPathEndIdx());
          let decimal = String((this.sliderVal / 100) * this.navg.getPathEndIdx()).split('.')[1] || 0
          this.navg.moveToPoint(num, Number('0.' + decimal));
          this.pathSimplifierIns.renderLater();
          if (num == this.navg.getPathEndIdx()) {
            this.isPlaying = false;
          }
        }
      },
      reset() {
        this.trackPath = [];
        this.isPlaying = false;
        this.sliderVal = 0;
        this.value = 1;
        this.speed = 100;
        // 如果巡航轨迹路线对象不为空
        if(Object.keys(this.pathSimplifierIns).length > 0) {
          // 销毁现存的所有轨迹巡航器
          this.pathSimplifierIns.clearPathNavigators();
          // 清空巡航轨迹数据
          this.pathSimplifierIns.setData();
        }
      },
      getPhoneLine(orderId){//手机轨迹
        this.reset();
        allTrail(orderId).then(res =>{
          if(res) {
            console.log("******获取的轨迹长度*****" + res);
            // 遍历，不进行轨迹纠偏
            res.data.forEach((element, index) => {
              if (element.type == 1){
                this.startMark = [element.longitude, element.latitude]
              } else if (element.type == 3){
                this.endMark = [element.longitude, element.latitude]
              }
              this.trackPath.push([element.longitude, element.latitude,element.createTime.replace(/-/g,"").replace(" ","/").replace(/:/g,"")])
            })
            // 初始化地图
            this.initMap();
          } else {
            this.msgError("获取轨迹失败")
          }
        })
      },
      // 先获取轨迹，再初始化地图
      getTrack(orderId) {//中交轨迹
        this.reset();
        getByOrder(orderId).then(res => {
          if(res) {
            console.log("******获取的轨迹长度*****" + res.length);
            // 遍历，不进行轨迹纠偏
            res.forEach((element, index) => {
              let lnglat = this.toLnglat(element.lon, element.lat);
              this.trackPath.push([lnglat.lng, lnglat.lat, element.gtm])
            })
            this.startMark = this.trackPath[0]
            this.endMark = this.trackPath[res.length-1];
            // 遍历，处理数据进行轨迹纠偏
            // for(let i = 0, ind = res.length/500; i < ind; i++) {
            //   let originPath = [];
            //   res.splice(0, 500).forEach((element, index) => {
            //     let lnglat = this.toLnglat(element.lon, element.lat);
            //     let origin = {
            //       "x": lnglat.lng,
            //       "y": lnglat.lat,
            //       "sp": Number(element.spd),
            //       "ag": Number(element.agl),
            //       "tm": 1478031031
            //     };
            //     // tm以秒为单位，第一个采集点的tm值从1970年0点开始，其他采集点为与第一个采集点时间的差值
            //     if(index > 0) {
            //       origin.tm = Number(accSub(tsGetDate(element.gtm.replace("/", "")).getTime()/1000, 1478031031));
            //     }
            //     originPath.push(origin);
            //   });
            //   // 轨迹纠偏
            //   this.grasp(originPath);
            // }

            // 初始化地图
            this.initMap();
          } else {
            this.msgError("获取轨迹失败")
          }
        })
      },
      // 坐标转换(WGS84坐标 -> GCJ-02坐标)
      toLnglat(lon, lat) {
        // 参数：经度、纬度、是否自动将经度值修正到 [-180,180] 区间内，缺省为false
        // 除以600000：文档中说明了单位为 1/600000.0
        return new AMap.LngLat(lon/600000, lat/600000, false);
      },
      // 轨迹纠偏(originPath示例: [{"x":116.478928,"y":39.997761,"sp":19,"ag":0, "tm":1478031031},{}])
      grasp(originPath) {
        var that = this;
        return new Promise((resolve, reject) => {
          AMap.plugin('AMap.GraspRoad',function(){
            var grasp = new AMap.GraspRoad();
            grasp.driving(originPath, function(error, result) {
              if(!error) {
                // return result.data.points; // 纠偏后的轨迹
                // var distance = result.data.distance; // 里程
                result.data.points.forEach(ele => {
                  that.trackPath.push([ele.x, ele.y]);
                })
              } else {
                console.log('轨迹纠偏报错: ')
                console.log(error)
                return null;
              }
            })
          })
        });
      },
      // 节点信息窗体
      pointInfo(map, arr, index) {
        this.getAddress(arr[index]).then(addr => {
          var infoWindow = new AMap.InfoWindow({
            // isCustom: true,
            anchor: 'middle-left',
            content: '<div>地点: ' + addr +
                     '</div><div>时间: ' + dateFormat(tsGetDate(arr[index][2].replace("/", ""))) +
                     '</div><div>路程: ' + accMul(accDiv(index, arr.length), 100).toFixed(1) +
                     '%</div>',
          });
          infoWindow.open(map, arr[index]);
        })
      },
      // 根据经纬度获取地址(lnglat示例: [116.396574, 39.992706])
      getAddress(lnglat) {
        return new Promise((resolve, reject) => {
          AMap.plugin('AMap.Geocoder', function() {
            var geocoder = new AMap.Geocoder({
              // city 指定进行编码查询的城市，支持传入城市名、adcode 和 citycode，默认全国
              // city: '010'
            })

            geocoder.getAddress(lnglat, function(status, result) {
              if (status === 'complete' && result.info === 'OK') {
                // result为对应的地理位置详细信息
                resolve(result.regeocode.formattedAddress);
              } else {
                resolve('未知');
              }
            })
          })
        })
      }
    }
  };
</script>
<style scoped>
  .map {
    height: 560px;
    width: 100%;
  }
</style>
